package com.util;

import com.alibaba.csb.sdk.ContentBody;
import com.alibaba.csb.sdk.HttpCaller;
import com.alibaba.csb.sdk.HttpParameters;
import com.alibaba.fastjson.JSON;
import com.config.Config;
import com.config.Configuration;
import com.consts.Const;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @author Smile
 */
@Slf4j
public class CsbUtil {
    private static final Config config = ConfigUtil.getConfig();
    private static final Configuration configuration = config.getCtfz();


    public static Map<String, Object> SendRequest(Const api, Object map) throws Exception {
        String host = configuration.getServiceMode() == 1 ? configuration.getTyywAddress() : configuration.getCsbAddress();
        String apiName = api.toString();
        if (configuration.getServiceMode() == 1) {
            return TyywRequest(host, configuration.getTyywUri().get(apiName), map);
        } else {
            return CsbRequest(host, configuration.getCsbUri().get(apiName), map);
        }
    }

    private static Map<String, Object> CsbRequest(String host, String api, Object paramsMap) throws Exception {
        log.info("调用CSB服务地址：" + host + "，调用接口名称：" + api);
        HttpParameters.Builder builder = new HttpParameters.Builder();
        builder.requestURL(host)
                .api(api)
                .version(configuration.getVersion())
                .method("post")
                .accessKey(configuration.getCsbAk())
                .secretKey(configuration.getCsbSk());
        ContentBody contentBody = new ContentBody(JSON.toJSONString(paramsMap));
        builder.contentBody(contentBody);
        String res = HttpCaller.invoke(builder.build());
        return (Map<String, Object>) JSON.parse(res);
    }


    private static Map<String, Object> TyywRequest(String host, String api, Object map) throws Exception {
        log.info("调用直连服务地址：" + host + "，调用接口名称：" + api);
        return HttpUtil.post(host + api, map);
    }
}
